package tgc.edu.exam.web.controller;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;

import tgc.edu.exam.custom.AjaxResult;
import tgc.edu.exam.custom.CommonController;
import tgc.edu.exam.custom.DataGridParam;
import tgc.edu.exam.custom.DataGridUtils;
import tgc.edu.exam.custom.LayUiResult;
import tgc.edu.exam.entity.CurriculumPlan;
import tgc.edu.exam.entity.Student;
import tgc.edu.exam.entity.SysRole;
import tgc.edu.exam.entity.SysUser;
import tgc.edu.exam.entity.TbClass;
import tgc.edu.exam.entity.TbCurriculum;
import tgc.edu.exam.entity.Teacher;
import tgc.edu.exam.security.UserUtils;
import tgc.edu.exam.service.CurriculumPlanService;
import tgc.edu.exam.service.StudentService;
import tgc.edu.exam.service.TbClassService;
import tgc.edu.exam.service.TbCurriculumService;
import tgc.edu.exam.service.TeacherService;
import tgc.edu.exam.web.form.CurriculumPlanForm;
import tgc.edu.exam.web.form.TbClassForm;

@Controller
@RequestMapping(value="/curriculumPlan")
public class CurriculumPlanController extends CommonController<CurriculumPlan, UUID, CurriculumPlanForm> {
	@Autowired
	private TbCurriculumService tcService;
	@Autowired
	private TbClassService tbClassService;
	@Autowired
	private TeacherService teacherService;
	@Autowired
	private UserUtils userUtils;
	@Autowired
	private CurriculumPlanService cpService;
	@Autowired
	private StudentService stuService;
	
	@Override
	public void manage(ModelMap map) {
		boolean ishas = false;
		/*SysUser sysUser = userUtils.getUser();
		if (sysUser == null) {
			ishas = true;
			List<TbClass> bjs = tbClassService.findAll();
			map.put("tbClass", bjs);
		} else {
			List<SysRole> roles = sysUser.getRoles();
			for (SysRole sysRole : roles) {
				List<SysRole> childrens = sysRole.getChildren();
				for (SysRole sysRole2 : childrens) {
					if (sysRole2.getCode() == "ROLE_KAOQINGEDIT") {
						ishas = true;
					}
				}
			}
			if(ishas) {
				List<TbClass> bjs = tbClassService.findAll();
				map.put("tbClass", bjs);
			}else {
				Specification<TbClass> spec = buildSpec3(sysUser);
				List<TbClass> bjs = tbClassService.findAll(spec);
				map.put("tbClass", bjs);
			}

		}*/
		map.put("tbClass", tbClassService.findAll());
		map.put("kc", tcService.findAll());
		map.put("teacher", teacherService.findAll());
		super.manage(map);
	}
	
	private Specification<TbClass> buildSpec3(SysUser sysUser) {
		Specification<TbClass> spec = new Specification<TbClass>() {
			private static final long serialVersionUID = 1L;

			@Override
			public Predicate toPredicate(Root<TbClass> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules = new HashSet<>();
				rules.add(cb.equal(root.get("teacherId").get("id"), sysUser.getId()));
				rules.add(cb.notEqual(root.get("classStatus").get("state"), "结业"));
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}
		};
		return spec;
	}
	
	/**
	 * 排课显示
	 */
	@RequestMapping(value="/preview")
	public void preview(String id, ModelMap map) {
		List<CurriculumPlan> cp = cpService.findByTbClassId(UUID.fromString(id));
		List<CurriculumPlan> clp = new ArrayList<CurriculumPlan>();
		//TbClass tbClass = tbClassService.findById(UUID.fromString(id));
		List<Student> stu = stuService.findByTbClassId(UUID.fromString(id));
		for(int i = 0; i < cp.size(); i++) {
			//Integer a = 0;
			Set<String> set = new HashSet<>();
			CurriculumPlan cp1 = cp.get(i);
			List<CurriculumPlan> cp2 = cpService.findByCurriculumIdAndTbClassClassStatusState(cp1.getCurriculum().getId(), "结业");
			for(int j = 0; j < cp2.size(); j ++) {
				CurriculumPlan cp3 = cp2.get(j);
				TbClass tbclass = cp3.getTbClass(); 
				List<Student> stu1 = stuService.findByTbClassId(tbclass.getId());
				for(int x = 0; x < stu.size(); x++) {
					for(int x1 = 0; x1 < stu1.size(); x1++) {
						if(stu.get(x).getIdcode().equals(stu1.get(x1).getIdcode())) {
							//a++;
							set.add(stu.get(x).getIdcode());
							break;
						}
					}
				}
			}
			cp1.setRs(set.size());
			clp.add(cp1);
		}
		map.put("tbkcData", clp);
	}

	@Override
	public void edit(CurriculumPlanForm form, ModelMap map) throws InstantiationException, IllegalAccessException {
		map.put("kc", tcService.findAll());
		map.put("tbClass", tbClassService.findAll());
		map.put("teacher", teacherService.findAll());
		super.edit(form, map);
	}
	
	/**
	 * 班级课程数据
	 */
	@RequestMapping(value="/tbClassKcData")
	public void tbClassKcData(String id, ModelMap map) {
		map.put("tbkcData", cpService.findByTbClassId(UUID.fromString(id)));
		map.put("kc", tcService.findAll());
		map.put("teacher", teacherService.findAll());
	}

	@Override
	public Object save(CurriculumPlanForm form) {
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			CurriculumPlan model=new CurriculumPlan();
			String name = userUtils.getName();
			UUID id = form.getId();
			if(id!=null) {
				model=cpService.findById(id);
				model.setUpdateDate(sdf.format(new Date()));
				model.setUpdateName(name);
			}else {
				model.setCreateDate(sdf.format(new Date()));
				model.setCreateName(name);
				model.setIsUsed(true);
			}
			BeanUtils.copyProperties(form, model,"id", "starttime", "finishttime");
			model.setStarttime(sdf.parse(form.getStarttime()));
			model.setFinishttime(sdf.parse(form.getFinishttime()));
			cpService.save(model);
			return new AjaxResult("数据保存成功");
		} catch (Exception e) {
			return new AjaxResult(false,"数据保存失败");
		}
	}
	
	@RequestMapping(value="/save1")
	@ResponseBody
	public Object save1(String data, String tbClassId) throws JsonParseException, JsonMappingException, IOException, ParseException {
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			ObjectMapper mapper = new ObjectMapper();
			List<CurriculumPlanForm> list =     
				       mapper.readValue(data,new TypeReference<List<CurriculumPlanForm>>() { });
			List<CurriculumPlan> curricu = cpService.findByTbClassId(UUID.fromString(tbClassId));
			for (CurriculumPlan c : curricu) {
				cpService.delete(c);
			}
			for(int i = 0; i < list.size(); i++) {
				CurriculumPlanForm cf = list.get(i);
				CurriculumPlan model = new CurriculumPlan();
				//Teacher t = teacherService.findById(UUID.fromString(cf.getTeacher1()));
				TbClass tc = tbClassService.findById(UUID.fromString(tbClassId));
				TbCurriculum tcl = tcService.findById(UUID.fromString(cf.getCurriculum1()));
				String data1 = cf.getStartdata();
				String time1 = cf.getFinishtime();
				String[] split = time1.split(" - ");
				String starttime = data1+" "+split[0];
				String finishttime = data1+" "+split[1];
				model.setStarttime(sdf.parse(starttime));
				model.setFinishttime(sdf.parse(finishttime));
				//model.setTeacher(t);
				model.setTbClass(tc);
				model.setCurriculum(tcl);
				model.setStartdata(data1);
				model.setFinishtime(time1);
				model.setIsUsed(true);
				cpService.save(model);
			}
			return new AjaxResult("数据保存成功");
		} catch (Exception e) {
			return new AjaxResult(false,"数据保存失败");
		}
	}
	
	/**
	 * 导出
	 * @param id
	 */
	@RequestMapping(value="/derive")
	@ResponseBody
	public void derive(String id, HttpServletRequest request, HttpServletResponse response) {
		List<CurriculumPlan> cp = cpService.findByTbClassId(UUID.fromString(id));
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet("课程安排");
		HSSFRow row1 = sheet.createRow(0);
		HSSFCellStyle cellstyle = workbook.createCellStyle();
		cellstyle.setAlignment(HorizontalAlignment.CENTER);
		cellstyle.setVerticalAlignment(VerticalAlignment.CENTER);
		
		HSSFFont font = workbook.createFont();
		font.setFontName("黑体");
		font.setFontHeightInPoints((short) 16);//设置字体大小
		cellstyle.setFont(font);
		
		//定义合并区间(起始行，结束行，起始列，结束列)
		CellRangeAddress region = new CellRangeAddress(0, 0, 0, 3);
		//合并单元格
		sheet.addMergedRegion(region);
		HSSFCell cell1 = row1.createCell(0);
		cell1.setCellValue("课程安排");
		cell1.setCellStyle(cellstyle);
		
		String[] fieldnames = {"日期", "时间", "课程", "老师"};
		HSSFRow row = sheet.createRow(1);
		for(int i = 0; i < fieldnames.length; i++) {
			HSSFCell cell = row.createCell(i);
			cell.setCellValue(fieldnames[i]);
		}
		for(int i = 0; i < cp.size(); i++) {
			row = sheet.createRow(i+2);
			HSSFCell cell = row.createCell(0);
			CurriculumPlan plan = cp.get(i);
			cell.setCellValue(plan.getStartdata());
			cell = row.createCell(1);
			cell.setCellValue(plan.getFinishtime());
			cell = row.createCell(2);
			cell.setCellValue(plan.getCurriculum().getCourseName());
			cell = row.createCell(3);
			cell.setCellValue(plan.getCurriculum().getTeacher().getName());
		}
		sheet.setColumnWidth(0, 20*256);
		sheet.setColumnWidth(1, 30*256);
		sheet.setColumnWidth(2, 50*256);
		sheet.setColumnWidth(3, 20*256);
		//定义Excel文件名
		String filename = "课程安排.xls";
		response.setHeader("Content-disposition", "attachment; filename=" + filename);
		response.setContentType("application/msexcel");
		try {
			//定义输出流，输出Excel
			ServletOutputStream outputStream = response.getOutputStream();
			workbook.write(outputStream);
			workbook.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public Specification<CurriculumPlan> buildSpec(CurriculumPlanForm form) {
		Specification<CurriculumPlan> specification = new Specification<CurriculumPlan>() {

			private static final long serialVersionUID = 1L;
			
			@Override
			public Predicate toPredicate(Root<CurriculumPlan> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules=new HashSet<>();
				if(StringUtils.hasText(form.getTacherName())) {
					Predicate name = cb.like(root.get("teacher").get("name"), "%"+form.getTacherName()+"%");
					rules.add(name);
				}
				if(StringUtils.hasText(form.getTbClassName())) {
					Predicate difficultylevel = cb.like(root.get("tbClass").get("name"), "%"+form.getTbClassName()+"%");
					rules.add(difficultylevel);
				}
				if(StringUtils.hasText(form.getKc())) {
					Predicate difficultylevel = cb.like(root.get("curriculum").get("courseName"), "%"+form.getKc()+"%");
					rules.add(difficultylevel);
				}
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}

		};
		return specification;
	}
	
}
